package com.controller.sys;


import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.base.BaseController;
import com.entity.sys.SysRole;
import com.entity.sys.SysUser;
import com.service.sys.SysMenuService;
import com.service.sys.SysRoleService;
import com.service.sys.SysUserService;
import fuhua.com.anno.CheckPermission;
import fuhua.com.anno.Log;
import fuhua.com.util.ResultUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * 角色信息
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController<SysRoleService,SysRole> {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysMenuService sysMenuService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @CheckPermission(perm = "system:role:view")
    public ResultUtil list(@RequestParam Map<String,String> map) {
        return ResultUtil.success(service.page(map));
    }

    /**
     * 根据id获取信息
     */
    @GetMapping("/getById/{id}")
    public ResultUtil getById(@PathVariable("id") String id) {
        return ResultUtil.success(service.getById(id));
    }

    /**
     * 生成角色代码
     */
    @Log(title = "生成角色代码")
    @GetMapping("/createDictCode")
    public ResultUtil createDictCode(String roleName) {
        String roleKey = PinyinUtil.getFirstLetter(roleName,"").toUpperCase();
        return ResultUtil.success(roleKey);
    }

    /**
     * 保存角色，同时保存角色与菜单关联、角色与部门关联
     */
    private void saveRole(SysRole role){
        // 没有设置数据范围时，根据角色设置默认数据范围权限
        if (Objects.isNull(role.getDataScope())){
            switch (role.getRoleKey()){
                case "CJGLY":role.setDataScope(1); break;
                case "GLY": role.setDataScope(2); break;
                case "PTYH": role.setDataScope(4); break;
                default: role.setDataScope(3); break;
            }
        }
        // 当数据范围为自定义数据，并且选择了具体部门时，新增角色与部门关联
        else if (role.getDataScope() == 5 && Objects.nonNull(role.getDeptIds())){
            service.insertRoleDept(role.getId(),role.getDeptIds());
        }
        service.saveOrUpdate(role); // 保存或更新角色信息
        // 保存角色与菜单关联
        service.insertRoleMenu(role.getId(),role.getMenuIds());
        sysMenuService.updateRolePerm(role.getId()); // 更新缓存中角色与菜单权限关联
    }

    /**
     * 新增
     */
    @Log(title = "新增角色")
    @PostMapping("/insert")
    @CheckPermission(perm = "system:role:add")
    public ResultUtil insert(@RequestBody SysRole role) {
        if (service.checkRoleNameAndKey(role.getRoleName(),null,role.getId())) {
            return ResultUtil.error("角色名称已存在");
        } else if (service.checkRoleNameAndKey(null,role.getRoleKey(),role.getId())) {
            return ResultUtil.error("角色代码已存在");
        }
        role.setId(service.createId());
        saveRole(role); // 保存角色，同时保存角色与菜单关联、角色与部门关联
        return ResultUtil.success();
    }

    /**
     * 修改
     */
    @Log(title = "修改角色")
    @PostMapping("/update")
    @CheckPermission(perm = "system:role:update")
    public ResultUtil update(@RequestBody SysRole role) {
        if (service.checkRoleNameAndKey(role.getRoleName(),null,role.getId())) {
            return ResultUtil.error("角色名称已存在");
        } else if (service.checkRoleNameAndKey(null,role.getRoleKey(),role.getId())) {
            return ResultUtil.error("角色代码已存在");
        }
        saveRole(role); // 保存角色，同时保存角色与菜单关联、角色与部门关联
        return ResultUtil.success();
    }

    /**
     * 删除
     */
    @Log(title = "删除角色")
    @DeleteMapping("/delete/{id}")
    @CheckPermission(perm = "system:role:delete")
    public ResultUtil delete(@PathVariable("id") String [] id) {
        for (String roleId : id) {
            SysRole role = service.getById(roleId);
            //通过角色ID查询角色使用数量
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.apply("FIND_IN_SET('"+roleId+"',role_id)");
            int count = sysUserService.count(queryWrapper);
            if (count>0){
                return ResultUtil.error(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }else {
                service.removeById(roleId);
            }
            //删除角色时，同时删除角色菜单关联
            service.insertRoleMenu(roleId,new String[0]);
            sysMenuService.deleteRolePerm(roleId);
            //删除角色时，同时删除角色部门关联
            service.insertRoleDept(roleId,new String[0]);
        }
        return ResultUtil.success();
    }

    /**
     * 角色下拉框
     */
    @GetMapping("/roleSelect")
    public ResultUtil roleSelect() {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        return ResultUtil.success(service.list(queryWrapper));
    }
}
